package message.receiver;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import message.monitor.Monitor;

/**
 * @ClassName Receiver
 * @Description TODO
 * @Author jihao
 * @Date 2020年6月5日 下午9:06:50
 * @Version 1.0
 */
public class Receiver {
	private static final String USERNAME=ActiveMQConnection.DEFAULT_USER; // 默认的连接用户名
    private static final String PASSWORD=ActiveMQConnection.DEFAULT_PASSWORD; // 默认的连接密码
    private static final String BROKEURL=ActiveMQConnection.DEFAULT_BROKER_URL; // 默认的连接地址
    ConnectionFactory cn=null;
    Connection connection=null;
    Session session=null;
    Destination destination=null;
    public void init()
    {
    	cn=new ActiveMQConnectionFactory(Receiver.USERNAME,
    			Receiver.PASSWORD,Receiver.BROKEURL);//处理冲突 调用activeMq工厂JMS通过这创建连接
    	try {
			connection=cn.createConnection();//生产者和消费者之间的连接
			connection.start();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    public void consumer()
    {
    	try {
    		MessageConsumer messageConsumer;
    		session=connection.createSession(true, Session.AUTO_ACKNOWLEDGE);//启动会话，true代表自动开启事务
    		destination=session.createQueue("Queue2");
    		messageConsumer=session.createConsumer(destination);//创建消费者到会话
    		messageConsumer.setMessageListener(new Monitor());//利用监听器处理生产者发送的消息
    		session.commit();//提交事务
	      //  System.in.read();
//    		messageConsumer.close();
//    		session.close();
//    		connection.close();
    	}
    	catch(JMSException e)
    	{
    		try {session.rollback();	} catch (JMSException e2) {e2.printStackTrace();}
    		e.printStackTrace();
    	}
    }
    public static void main(String[] args) {
		// TODO Auto-generated method stub
    	Receiver jch=new Receiver();
			jch.init();//创建连接
			jch.consumer();//执行消费者的操作
	}

}
